package org.homly.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.upload.FormFile;

public class UploadFileTool {
	public static final String UPLOAD_DIR = "product_pic";
	public static final String UPLOAD_EXT_DIR = "product_pic_ext";

	public static String uploadFile(HttpServletRequest request,
			FormFile formFile) {
		return UploadFileTool.uploadFile(request, formFile, 0);
	}

	/**
	 * 上传产品图片
	 * 
	 * @param request
	 * @param formFile
	 * @param type
	 *            0：普通图片 1：附加图片
	 * @return
	 */
	public static String uploadFile(HttpServletRequest request,
			FormFile formFile, int type) {

		if (formFile == null) {
			return null;
		}
		String webRoot = request.getSession().getServletContext()
				.getRealPath("/");
		String dir = (type == 0 ? UploadFileTool.UPLOAD_DIR :
				UploadFileTool.UPLOAD_EXT_DIR);
		InputStream is = null;
		OutputStream os = null;
		try {
			String dirRealPath = webRoot + dir + File.separator;
			File file = new File(dirRealPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String fileName = System.currentTimeMillis() + "_"
					+ formFile.getFileName();
			String fullPath = dirRealPath + fileName;
			is = formFile.getInputStream();
			os = new FileOutputStream(new File(fullPath));
			int readSize = 0;
			byte buffer[] = new byte[1024];
			while ((readSize = is.read(buffer, 0, 1024)) != -1) {
				os.write(buffer, 0, readSize);
			}
			String url = "/" + dir + "/" + fileName;

			return url;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
				is = null;
			}
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
				os = null;
			}
		}
	}

	public static String getFileBasicName(String fileName) {

		String fileBasicName = "";
		try {
			fileBasicName = fileName.substring(0, fileName.lastIndexOf("."));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fileBasicName;
	}
}
